package com.example.demosecuritycontext.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 方法级别的权限配置许可
public class SecurtiyConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        // 链式编程
        // 首页所有人都可以访问，功能也只有对应有权限的人才能访问到
        // 请求授权的规则
        http
                .authorizeRequests()
                // 首页所有人可以访问
                .anyRequest().authenticated()
                // 特定权限访问页
//                .antMatchers("/user/query").hasAnyAuthority("query")
//                .antMatchers("/user/delete").hasAnyAuthority("delete")
//                .antMatchers("/user/update").hasAnyAuthority("update")
//                .antMatchers("/user/insert").hasAnyAuthority("insert")
//                .antMatchers("/user/export").hasAnyAuthority("export")
                .and()
                // 无权限默认跳转登录页
                .formLogin();

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        // 密码加密
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        // 设置用户
        UserDetails user1 = User.builder()
                .username("dong")
                .password(encoder.encode("123456"))
                // 用户权限
                .roles("user")
                .authorities("query","export")
                .build();

        UserDetails user2 = User.builder()
                .username("fan")
                .password(encoder.encode("123456"))
                // 用户权限
                .roles("admin")
                .authorities("query","delete","update","insert")
                .build();

        return new InMemoryUserDetailsManager(user1,user2);
    }

}
